package com.fsd.admin.controller;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fsd.core.util.*;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fsd.admin.entity.A_LoginInfo;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.service.A_EmployeeService;
import com.fsd.admin.model.A_Company;
import com.fsd.admin.service.A_CompanyService;
import com.fsd.admin.service.Sys_SystemLogService;
import com.fsd.admin.service.Sys_SystemMenuService;
import com.fsd.admin.service.Sys_PopedomAllocateService;
import com.fsd.core.common.BusinessException;
import com.google.gson.Gson;

/**
 * 公共控制器
 * @author lumingbao
 */

@Controller
@RequestMapping("/admin/Common")
public class CommonController  extends AdminController{
	
	private static final Logger log = Logger.getLogger(CommonController.class);
	
	@Resource(name = "Sys_SystemMenuServiceImpl")
	private Sys_SystemMenuService sys_SystemMenuService;
	
	@Resource(name = "Sys_PopedomAllocateServiceImpl")
	private Sys_PopedomAllocateService sys_PopedomAllocateService;
	
	@Resource(name = "A_EmployeeServiceImpl")
	private A_EmployeeService a_EmployeeService;
	
	@Resource(name = "A_CompanyServiceImpl")
	private A_CompanyService objectService;
	
    @Resource(name = "Sys_SystemLogServiceImpl")
    private Sys_SystemLogService sysLogService;

	/**
	 * 用户登陆
	 * @author lumingbao
	 * @param request
	 * @param Loginname 用户名
	 * @param Password 用户密码
	 * @param code 验证码
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user_login.do")
	public @ResponseBody Object Login(HttpServletRequest request , String Loginname , String Password , String code) throws Exception{
		A_Employee user = a_EmployeeService.getObjectLogin(Loginname, Password);
		if(user == null){
			throw new BusinessException("用户名或密码错误！");
		}
		A_LoginInfo loginInfo = new A_LoginInfo();
		loginInfo.setEmployee(user);
		A_Company company = objectService.getObjectById(user.getCompanyid());
		loginInfo.setCompany(company);
		Map<String, List<String>> popedomMap = sys_PopedomAllocateService.getUserPopedomMap(user);
		loginInfo.setPopedomMap(popedomMap);
		request.getSession().setAttribute(Config.LOGININFO, loginInfo);
		this.sysLogService.saveObject(Config.LOGTYPEDL, user.getId() + user.getRealname(), user, CommonController.class);
		return ParametersUtil.sendList();
	}
	
	/**
	 * 注销登陆
	 * @author lumingbao
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/user_loginout.do")
	public @ResponseBody Object Loginout(HttpServletRequest request){
		request.getSession().removeAttribute(Config.LOGININFO);
		return ParametersUtil.sendList();
	}
	
	/**
     * 加载用户菜单
     * @author lumingbao
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/user_menu.do")
    public @ResponseBody Object getUserMenu(HttpServletRequest request) throws Exception{
    	return ParametersUtil.sendList(
    			sys_SystemMenuService.getUserMenu(
    					((A_LoginInfo)request.getSession().getAttribute(Config.LOGININFO)).getEmployee(),
    					((A_LoginInfo)request.getSession().getAttribute(Config.LOGININFO)).getPopedomMap().get("qxlxcd")
    					));
    }
    
    /**
     * 加载带复选框的用户菜单
     * @author lumingbao
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/user_checkMenu.do")
    public @ResponseBody Object getCheckUserMenu(HttpServletRequest request) throws Exception{
    	return ParametersUtil.sendList(
    			sys_SystemMenuService.getUserCheckMenu(
    					((A_LoginInfo)request.getSession().getAttribute(Config.LOGININFO)).getEmployee(),
    					((A_LoginInfo)request.getSession().getAttribute(Config.LOGININFO)).getPopedomMap().get("qxlxcd")
    					));
    }
    
    /**
     * 加载全局参数
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/all_getAllInfo.do")
    public @ResponseBody Object getAllInfo(HttpServletRequest request) throws Exception{
    	A_LoginInfo loginInfo = (A_LoginInfo)request.getSession().getAttribute(Config.LOGININFO);
    	ParametersUtil util = new ParametersUtil();
    	util.addSendObject("user", loginInfo.getEmployee());
    	util.addSendObject("company", loginInfo.getCompany());
    	util.addSendObject("popedom", loginInfo.getPopedomMap());
    	return util.sendObject();
    }

    /**
     * 汉字转拼音
     * @param parameters
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/all_hanziToPinyin.do")
    public @ResponseBody Object HanziToPinyin(ParametersUtil parameters) throws Exception{
    	Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("key") == null || "".equals(objectMap.get("key"))){
			throw new BusinessException("获取缺少key参数!");
		}
    	return ParametersUtil.sendList(PinyinUtil.getPinYinHeadChar(objectMap.get("key").toString()));
    }
    
    /**
     * 获取系统信息
     */
    @RequestMapping(value = "/get_sysInfo.do")
    public @ResponseBody Object getSysInfo() throws Exception{
    	Properties props = System.getProperties();
    	Runtime r = Runtime.getRuntime();
    	
    	List<Map<String, String>> list = new ArrayList<Map<String,String>>();
    	
    	Map<String, String> map = new HashMap<String, String>();
		map.put("key", "JVM可以使用的总内存:");
		map.put("value", String.valueOf(r.totalMemory()));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "JVM可以使用的剩余内存:");
		map.put("value", String.valueOf(r.freeMemory()));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "JVM可以使用的处理器个数:");
		map.put("value", String.valueOf(r.availableProcessors()));
		list.add(map);
		
    	map = new HashMap<String, String>();
		map.put("key", "Java的运行环境版本:");
		map.put("value", props.getProperty("java.version"));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "Java的运行环境供应商:");
		map.put("value", props.getProperty("java.vendor"));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "Java的安装路径:");
		map.put("value", props.getProperty("java.home"));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "Java的虚拟机规范版本:");
		map.put("value", props.getProperty("java.vm.specification.version"));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "Java的虚拟机规范供应商:");
		map.put("value", props.getProperty("java.vm.specification.vendor"));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "操作系统的名称:");
		map.put("value", props.getProperty("os.name"));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "操作系统的构架:");
		map.put("value", props.getProperty("os.arch"));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "操作系统的版本:");
		map.put("value", props.getProperty("os.version"));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "文件分隔符:");
		map.put("value", props.getProperty("file.separator"));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "路径分隔符:");
		map.put("value", props.getProperty("path.separator"));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "行分隔符:");
		map.put("value", props.getProperty("line.separator"));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "用户的账户名称:");
		map.put("value", props.getProperty("user.name"));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "用户的主目录:");
		map.put("value", props.getProperty("user.home"));
		list.add(map);
		
		map = new HashMap<String, String>();
		map.put("key", "用户的当前工作目录:");
		map.put("value", props.getProperty("user.dir"));
		list.add(map);
    	return ParametersUtil.sendList(list);
    }
    
    /**
     * 生成静态页
     * @param parameters
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/makeHtml.do")
    public @ResponseBody Object makeHtml(ParametersUtil parameters, HttpServletRequest request) throws Exception {
    	Gson gs = new Gson();
    	Map objectMap = (Map)gs.fromJson(parameters.getJsonData(), Map.class);
    	if ((objectMap.get("companyid") == null) || ("".equals(objectMap.get("companyid")))) {
    		throw new BusinessException("获取缺少companyid参数!");
    	}
    	String companyid = objectMap.get("companyid").toString();
    	String rootPath = getRootPaht(request.getSession());
    	if (!"FSDCOMPANY".equals(companyid)) {
    		File file = new File(rootPath + "/" + companyid);
    		if ((!file.exists()) && (!file.isDirectory())) {
    			file.mkdir();
    		}
    	}

    	String path = request.getContextPath();
    	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    	HtmlGenerator html = new HtmlGenerator();
    	if ("FSDCOMPANY".equals(companyid)){
    		html.createHtmlPage(basePath + "index.htm", rootPath + "/index.html");
    	}
    	else {
    		html.createHtmlPage(basePath + companyid + "/index.htm", rootPath + "/" + companyid + "/index.html");
    	}
    	return ParametersUtil.sendList();
    }

	/**
	 * 清理缓存
	 * @param parameters
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/cleanCache.do")
	public @ResponseBody Object cleanCache(ParametersUtil parameters, HttpServletRequest request) throws Exception {
		EhcacheUtil.getInstance().removeAll();
		return ParametersUtil.sendList();
	}

	/**
	 * 加载文件
	 * @param path
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/download.do")
	public HttpServletResponse download(String path, HttpServletRequest request, HttpServletResponse response) {
		try {
			// path是指欲下载的文件的路径。
			File file = new File(this.getRootPaht(request.getSession()) + path);
			// 取得文件名。
			String filename = file.getName();
			// 取得文件的后缀名。
			String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return response;
	}

	/**
	 * 解析WORD到HTML
	 * @param request
	 * @param url 已经上传的word文件路径
	 * @param clean_format 清除格式
	 * @param text_indent 首行缩进
	 * @param clean_fontsize 清除字号
	 * @param clean_font 清除字体
	 * @param clean_image 清除图片
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/analysisFile.do")
	public @ResponseBody Object analysisFile(HttpServletRequest request, String url, int clean_format, int text_indent, int clean_fontsize, int clean_font, int clean_image, int clean_a) throws Exception {
		String rootPaht = this.getRootPaht(request.getSession());
		String html = Doc2Html.toHtmlString(new File(rootPaht + url), rootPaht + "uploadfiles/file", clean_format, text_indent, clean_fontsize, clean_font, clean_image, clean_a);
		html = html.replaceAll(rootPaht, "/");
		return ParametersUtil.sendList(html);
	}
}
